const { chromium } = require('playwright');
const { URLSearchParams } = require('url');

async function execPlaywright(browserWSEndpoint) {
  try {
    const browser = await chromium.connectOverCDP(browserWSEndpoint);
    const [page] = browser.contexts()[0].pages();
    // const page = await browser.newPage();
    await page.goto('https://nstbrowser.io/');
    // await page.screenshot({path: 'screenshot.png'});
    // await browser.close();
  } catch (err) {
    console.error(err);
  }
}

// ConnectBrowser: Launch and connect to a running browser or a created profile
async function launchAndConnectToBrowser(profileId) {
  const host = 'localhost:8848';
  const apiKey = '7be6d900-d38c-4dcd-b2dd-45632a0266fc';
  const config = {
    headless: false, // support: true or false
    autoClose: true,
  };
  const query = new URLSearchParams({
    'x-api-key': apiKey, // required
    config: encodeURIComponent(JSON.stringify(config)),
  });
  const browserWSEndpoint = `ws://${host}/api/v2/connect/${profileId}?${query.toString()}`;
  console.log('browserWSEndpoint: ', browserWSEndpoint);
  await execPlaywright(browserWSEndpoint);
}

launchAndConnectToBrowser('e1adca1c-2aa2-461b-9336-eb63f8c93dda').then();